from detect_image_wn import run_init,run_detect
from flask import request, Flask
import numpy as np
import json
import base64
from gevent import pywsgi
import cv2
from queue import Queue
import threading
import msvcrt
import sys


# 使用类创建结构体 存储name 与图像
class Name_Imag_Class(object):
    class Struct(object):
        def __init__(self, name, image):
            self.name = name
            self.image = image

    def make_struct(self, name, image):
        return self.Struct(name, image)

#全局变量
image_q = Queue(maxsize=0)  #创建队列，存储图像
result_q = {}  #创建字典，存储识别结果，name:string

########################### http 传图 #######################################
app = Flask(__name__)
@app.route("/", methods=['POST'])
def get_frame():
    #start_time = time.time()
    upload_file = request.get_data()
    req = json.loads(upload_file)
    
    
    if upload_file:
        name = req['name']
        wait = req['wait']
        img_str = req['image'] #得到unicode的字符串

        if (wait==0):
            img_decode_ = img_str.encode('ascii') #从unicode变成ascii编码
            img_decode = base64.b64decode(img_decode_) #解base64编码，得图片的二进制
            img_np_ = np.frombuffer(img_decode, np.uint8)
            img = cv2.imdecode(img_np_, cv2.COLOR_RGB2BGR) #转为opencv格式
            name_imag_class = Name_Imag_Class()
            img_struct=name_imag_class.make_struct(name,img)
            image_q.put(img_struct)
            return 'success'
        if (wait==1):
            name_string=result_q.get(name)#获取对应name的字典数据
            if(name_string==None):
                return 'no result'
            else:
                result_q.pop(name)#返回结果，清空对用字典缓存
                print(result_q)
                return name_string
             

        
    else:
        return 'failed'

def http_image():
    server = pywsgi.WSGIServer(('127.0.0.1', 6060), app)
    print("server is open\r\n")
    server.serve_forever()    
########################### http 传图 end ######################################

########################### 图像识别 ############################################
def detect():
    while 1:
        if(image_q.empty()==False):
            
            imge=image_q.get()
            s=run_detect(imge.image ,device,half,model,stride,imgsz,names)
            result_q[imge.name]=s
            print(result_q)
            print(list(result_q.keys()))
            print(list(result_q.values()))

########################### 图像识别 end ############################################



if __name__ == "__main__":

    device,half,model,stride,imgsz,names=run_init()
    print("detect modle is init finsh\r\n")

    thread_http_image = threading.Thread(target=http_image)
    thread_detect = threading.Thread(target=detect)
    
    thread_detect.start() 
    thread_http_image.start()  

    thread_detect.join()
    thread_http_image.join()  
    
    # while(1):
    #     pass